<template>
  <basic-dialog :visible="show"
                :title="`修改${statusList[1].label}原因`"
                min-width="400px"
                max-width="400px"
                :isFullScreen="false"
  >
    <q-form @submit="submit" greedy class="q-gutter-md dialog-content">
        <div style="padding: 20px 20px 0">
          <yz-input v-model="stopType"
                    :rules="[0]"
                    inputType="select"
                    :hint-rule="[val => val !== null || '不能为空']"
                    :options="stopTypeList"
                    :title="`${statusList[1].label}类型`"/>
          <yz-input v-model="stopCause"
                    :rules="[0]"
                    inputType="select"
                    :hint-rule="[val => !!val || '不能为空']"
                    :options="stopCauseList"
                    :title="`${statusList[1].label}原因`"/>
          <select-tree label="所在部门" :sel-tree="selDepartment" ref="selectTree"
                       :tree-list="departments" node-key="id"
                       @treeChange="_changeTreeNode" />
          <fuzzy-search
            v-model.trim="operatorId"
            :fuzzyParams="fuzzyParams"
            fuzzyNumber="keyword"
            :isShowValue="false"
            :fuzzyObj="['name', 'id']"
            showAllOption
            :title="`${statusList[1].label}人员`"
            :options="userList"
            :fuzzyFunc="getUserFilter"
            @onSelect="getCurrentUserList"
          ></fuzzy-search>
          <yz-input input-type="textarea" v-model="remark" :maxlength="100" title="备注信息"/>
        </div>
        <q-separator />
        <div class="dialog-footer text-center margin-t-10">
          <q-btn outline label="取消" color="primary" @click="$emit('close'); operatorId='', selDepartment.label = null " class="q-mr-md"/>
          <q-btn unelevated label="确认" color="primary" type="submit" :loading="submitting"/>
        </div>
      </q-form>
  </basic-dialog>
</template>

<script>
import { getCauseItemNew, getCauseTypeList } from '../../../boot/system/reason'
import { editDowntimeDuration } from '../../../boot/status-monitor/machine'
import userManageApi, { getUserFilter } from '../../../boot/system/user-manage'
import SelectTree from 'src/components/select-tree'
import { putBatchReport } from '../../../boot/statistics/stop-stat'
import { mapGetters } from 'vuex'
export default {
  name: 'edit-detail',
  props: {
    show: {
      type: Boolean,
      default: false,
      required: true
    },
    data: {
      required: true
    },
    selectedReport: Array,
    isReports: {
      type: Boolean,
      default: false
    },
    isFilter: {
      type: Boolean
    }
  },
  components: {
    SelectTree
  },
  computed: {
    ...mapGetters(['statusList'])
  },
  data () {
    return {
      deviceId: null,
      submitting: false,
      stopType: null,
      stopTypeDetail: {},
      stopTypeList: [], // 停机原因类型
      stopCause: null,
      stopCauseList: [],
      stopCauseDetail: {},
      remark: '',
      operatorId: null,
      userList: [], // 用户，
      currentUserList: [],
      selDepartment: {}, // 所在位置
      departments: [], // 部门列表
      getUserFilter: getUserFilter,
      fuzzyParams: {
        pageNum: 1,
        pageSize: 100000,
        departmentId: '',
        searchBy: 'name'
      }
    }
  },
  created () {
    this.getStopcauseList()
    this.getDepartmentsTree()
  },
  methods: {
    _changeTreeNode (val) {
      this.operatorId = ''
      this.userList = []
      if (val.id && val.label) {
        this.selDepartment.id = val.id
        this.selDepartment.level = val.level
        this.selDepartment.label = val.label
        this.fuzzyParams.departmentId = val.id
      }
    },
    // 修改停机原因
    changeType () {
      this.getCauseItem(true)
    },
    /**
     * 获取部门 tree
     */
    getDepartmentsTree: function () {
      userManageApi.getDepartmentsTree().then(res => {
        let departments = res.filter(item => item.type !== 'cc' && item.type !== 'cg')
        this.departments = departments
      })
    },
    // 获取原因类型列表
    getStopcauseList () {
      getCauseTypeList(3, this.isFilter).then(res => {
        if (res.data.length > 0) {
          res.data.forEach(o => {
            // 让步原因类型map（为取让步名）
            this.stopTypeDetail[o.id] = o.label
            this.stopTypeList.push({
              value: o.id,
              label: o.label
            })
          })
          if (!this.data && (this.data && !this.data.typeId)) {
            if (res.data[0]) {
              this.$nextTick(() => {
                this.stopType = res.data[0].id
              })
            }
          }
        }
      })
    },
    // 根据停机原因类型代码查询停机原因
    getCauseItem (isChange) {
      const typeId = this.stopType
      const params = {
        id: typeId,
        showDisable: false
      }
      this.stopCauseList = []
      this.stopCauseDetail = {}
      this.stopCause = ''
      getCauseItemNew(params).then(res => {
        if (res.data.length > 0) {
          res.data.forEach(o => {
            this.stopCauseDetail[o.id] = o.label
            this.stopCauseList.push({
              value: o.id,
              label: o.label
            })
          })
          if ((this.data && this.data.causeId && this.data.causeId !== -1) && !this.isReports && !isChange) {
            this.$nextTick(() => {
              const index = this.stopCauseList.findIndex(item => item.value === this.data.causeId)
              if (index < 0) {
                this.stopCauseList.unshift({
                  value: this.data.causeId,
                  label: this.data.stopCause
                })
                this.stopCauseDetail[this.data.causeId] = this.data.stopCause
              }
              this.stopCause = this.data.causeId
            })
          } else if ((this.data && !this.data.causeId) && !isChange) {
            this.$nextTick(() => {
              this.stopCause = res.data[0].id
            })
          } else if (isChange || this.isReports) {
            this.$nextTick(() => {
              this.stopCause = res.data[0].id
            })
          }
        } else {
          this.stopCause = null
        }
      })
    },
    getCurrentUserList (val, option) {
      this.currentUserList = option
    },
    submit () {
      this.submitting = true
      let params = {
        timeStamp: this.data.timeStamp,
        typeId: this.stopType,
        type: this.stopTypeDetail[this.stopType],
        causeId: this.stopCause,
        cause: this.stopCauseDetail[this.stopCause],
        remark: this.remark
      }
      if (this.operatorId) {
        const userList = [...this.currentUserList, ...this.userList]
        params['operatorId'] = this.operatorId
        params['operatorName'] = userList.find(item => item.id === this.operatorId) ? userList.find(item => item.id === this.operatorId).name : ''
        params['deptId'] = this.selDepartment.id
      } else {
        params['operatorId'] = ''
        params['operatorName'] = ''
        params['deptId'] = ''
      }
      if (this.isReports) {
        const timeStamp = this.selectedReport.map(v => v.timeStamp)
        const list = []
        for (let i = 0; i < timeStamp.length; i++) {
          params.timeStamp = timeStamp[i]
          list.push({ ...params })
        }
        putBatchReport(list).then(res => {
          if (res.code === '1200') {
            this.$emit('getList')
            this.$emit('close')
            this.$message.success('编辑成功')
            this.submitting = false
          }
        })
      } else {
        editDowntimeDuration(this.deviceId, params).then(res => {
          if (res.code === '1200') {
            this.$emit('getList')
            this.$emit('close')
            if (this.data.causeId === -1) {
              this.$emit('fillIn')
            }
            this.submitting = false
            this.$message.success('编辑成功')
          }
        })
      }
    },
    reorganize (node) {
      if (node.id === this.data.deptId) {
        this.selDepartment.id = node.id
        this.selDepartment.level = node.level
        this.selDepartment.label = node.label
      }

      if (node.children instanceof Array && !this.selDepartment.id) {
        node.children.forEach(this.reorganize)
      }
    }
  },
  watch: {
    show (val) {
      if (val) {
        this.deviceId = this.data.deviceId
        this.remark = !this.isReports ? this.data.remark : ''
        if (this.data.typeId && !this.isReports && this.data.typeId !== -1) {
          this.stopType = this.data.typeId
          this.getCauseItem()
        } else {
          this.stopType = this.stopTypeList.length > 0 ? this.stopTypeList[0].value : null
          this.stopTypeList.length && this.getCauseItem(true)
        }
        if (!this.isReports) {
          if (this.data.operatorId) {
            this.selDepartment.id = null
            // 确定部门所在位置
            this.departments.forEach(this.reorganize)
            this.operatorId = this.data.operatorId
            this.userList = [{ name: this.data.stopPerson, id: this.data.operatorId }]
          } else {
            this.selDepartment.id = this.departments[0].id
            this.selDepartment.level = this.departments[0].level
            this.selDepartment.label = this.departments[0].label
            this.operatorId = null
          }
        } else {
          this.selDepartment.id = ''
          this.selDepartment.level = ''
          this.selDepartment.label = ''
          this.operatorId = null
        }
        this.fuzzyParams.departmentId = this.selDepartment.id
        this.$nextTick(() => {
          this.$refs.selectTree.setValue(this.selDepartment)
        })
      } else {
        this.stopType = null
      }
    },
    stopType (val, oldVal) {
      if (val && oldVal) {
        this.changeType()
      }
    }
  }
}
</script>

<style scoped lang="stylus">
/deep/ .form-name {
  text-align right
  font-size 16px
  display inline-block
  width 82px
  color #333
  line-height: 31px
}
/deep/ .input-select{
  margin-bottom 0!important;
}
/deep/ .name{
  font-size: 16px;
}
</style>
